package com.neighbor.neighborhooduser.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neighbor.neighborhooduser.pojo.PostCollections;
import com.neighbor.neighborhooduser.pojo.PostLikes;
import com.neighbor.neighborhooduser.pojo.Posts;
import com.neighbor.neighborhooduser.dao.IPostsDao;
import com.neighbor.neighborhooduser.pojo.Users;
import com.neighbor.neighborhooduser.service.IPostCollectionsService;
import com.neighbor.neighborhooduser.service.IPostLikesService;
import com.neighbor.neighborhooduser.service.IPostsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neighbor.neighborhooduser.utils.ReOpe;
import com.neighbor.neighborhooduser.utils.ResponseMsg;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 用户帖子表 服务实现类
 * </p>
 *
 * @author song
 * @since 2025-09-22 09:13:04
 */
@Service
public class PostsServiceImpl extends ServiceImpl<IPostsDao, Posts> implements IPostsService {

    @Autowired
    private IPostsDao postsDao;
    @Autowired
    private ReOpe reOpe;
    @Autowired
    private IPostLikesService postLikesService;
    @Autowired
    private IPostCollectionsService postCollectionsService;


    @Override
    public List<Posts> getPosts(Integer page, Integer pageSize, Integer type, String title, String nickname, HttpServletRequest request) {
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {
            return null;
        }
        List<Posts> posts = postsDao.selectPostsWithUser(page, pageSize, type, title, nickname);
        return insertParam(responseMsg, posts);
    }


    /**
     * 根据ID获取帖子详情。
     * @param postId 帖子ID
     * @return ResponseMsg 包含帖子详情的响应。
     */
    @Override
    public ResponseMsg getPostById(Integer postId,HttpServletRequest request) {
        // 调用自定义mapper方法执行连表查询，获取带用户信息的帖子
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {
            return null;
        }
        Posts post = postsDao.getPostWithUserById(postId);
        if (post == null) {
            return ResponseMsg.getInstance(ResponseMsg.PARAMETER_ERROR, "未找到该帖子");
        }
        List<Posts> posts = insertParam(responseMsg, Collections.singletonList(post));
        return ResponseMsg.getInstance(ResponseMsg.SUCCESS, "成功获取帖子详情", posts.get(0));
    }

    @Override
    public List<Posts> getHotPosts(Integer page, Integer pageSize,HttpServletRequest request) {
        int offset = (page - 1) * pageSize;
        ResponseMsg responseMsg = reOpe.IsToken(request);
        if (responseMsg.getCode() != ResponseMsg.SUCCESS) {
            return null;
        }
        List<Posts> posts = postsDao.getHotPosts(offset, pageSize);
        return insertParam(responseMsg, posts);
    }

    private List<Posts> insertParam(ResponseMsg responseMsg, List<Posts> posts) {
        for(Posts p : posts){
            Users user = (Users) responseMsg.getData();
            QueryWrapper<PostLikes> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", user.getUserId())
                    .eq("post_id", p.getPostId());
            long count = postLikesService.count(wrapper);
            QueryWrapper<PostCollections> CollectWrapper = new QueryWrapper<>();
            CollectWrapper.eq("user_id", user.getUserId())
                    .eq("post_id", p.getPostId());
            long collectCount = postCollectionsService.count(CollectWrapper);
            p.setIsLiked(count != 0);
            p.setIsCollected(collectCount != 0);
        }

        return posts;
    }

    @Override
    public IPage<Posts> getPostsByUserId(Page<Posts> page, Integer userId) {
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .ne("status", 3) // 排除已删除的帖子
                .orderByDesc("created_at");
        return this.page(page, wrapper);
    }

    @Override
    public IPage<Posts> getPostsByUserIdAndStatus(Page<Posts> page, Integer userId, Integer status) {
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("status", status)
                .orderByDesc("created_at");
        return this.page(page, wrapper);
    }

    @Override
    public long countPostsByUserId(Integer userId) {
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .ne("status", 3); // 排除已删除的帖子
        return this.count(wrapper);
    }

    @Override
    public long countPostsByUserIdAndStatus(Integer userId, Integer status) {
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .eq("status", status);
        return this.count(wrapper);
    }
}
